import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { StorageKey } from '../utils/enum'
import { Log } from '@/types/log'
import dayjs from 'dayjs'

export const useLogStore = defineStore('log', () => {
  const logData = ref<Log[]>([])

  const viewData = computed(() => {
    return logData.value
  })

  // 初始化
  const initData = async () => {
    let _data = []

    try {
      const localRs = await localStorage.getItem(StorageKey.LOG_DATA)
      if (localRs) {
        _data = JSON.parse(localRs)
      } else {
        // @ts-ignore
        _data = []
      }
      logData.value = _data
    } catch (error) {
      console.error(error)
    }
  }

  // 添加日志
  const addLog = (log: Log) => {
    if (log.isTop) {
      const topIndex = logData.value.findIndex((item) => item.isTop)
      if (topIndex !== -1) {
        readTopLog(logData.value[topIndex])
      }
    }
    if (!log.time) {
      log.time = dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
    // 随机生成id
    log.id = crypto.randomUUID()
    logData.value.unshift(log)

    return log.id
  }

  // 删除id
  const deleteLog = (id: string) => {
    const _index = logData.value.findIndex((item) => item.id === id)
    if (_index !== -1) {
      logData.value.splice(_index, 1)
    }
  }

  // 修改日志
  const updateLog = (id: string, log: any) => {
    const _index = logData.value.findIndex((item) => item.id === id)
    if (_index !== -1) {
      Object.assign(logData.value[_index], log)
    }
  }

  // 获取日志
  const getLog = (id: string) => {
    const _index = logData.value.findIndex((item) => item.id === id)
    if (_index !== -1) {
      return logData.value[_index]
    }
    return null
  }

  // 置顶已读
  const readTopLog = (log: Log) => {
    const _index = logData.value.findIndex(
      (item) => item.time === log.time && item.isTop
    )
    if (_index !== -1) {
      logData.value[_index].isTop = false
    }
  }

  return {
    data: logData,
    viewData,
    initData,
    addLog,
    readTopLog,
    deleteLog,
    updateLog,
    getLog,
  }
})
